package com.yaopaikeji.config;

import com.yaopaikeji.exception.BaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class AsyncConfig {

    private static Logger logger = LoggerFactory.getLogger(AsyncConfig.class);

    @Bean
    public AsyncTaskExecutor asyncTaskExecutor(){

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        executor.setThreadNamePrefix("My-Executor");
        executor.setMaxPoolSize(10);
        executor.setCorePoolSize(3);

        executor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {

                logger.error("系统资源不足，无法发送更多邮件"+executor.toString());
                throw new BaseException();
            }
        });

        return executor;
    }
}
